//
//  HR_BLELinkManager.m
//  Pods
//
//  Created by xiaoming on 17/07/24.
//
//

#import "HR_BLELinkManager.h"
#import "HR_BLELinkTools.h"
#import "HR_BLELinkInfoModel.h"

/** 起始码 */
static const int startCode = 0x02;
/** 终止码 */
static const int endCode = 0x03;

@interface HR_BLELinkManager ()

/** Notice charateristic, Write charateristic */
@property (nonatomic, strong) CBCharacteristic *notiC, *writeC;
/** 外设 */
@property (strong, nonatomic) CBPeripheral *peripheral;
/** 是否为第一次写入‘获取设备信息’ */
@property (assign, nonatomic) BOOL isFirstCommandType_SYS_INFO;
/** threadForTimer */
@property (strong, nonatomic) NSThread *threadForTimer;
/** 当前跑步机速度 */
@property (assign, nonatomic) int speed;
/** 传入跑步机坡度信息 */
@property (assign, nonatomic) int gradient;

@end

@implementation HR_BLELinkManager

- (instancetype)initWithPrepheral:(CBPeripheral *)peripheral {
    self = [super init];
    if (self) {
        _peripheral = peripheral;
        _isFirstCommandType_SYS_INFO = YES;
    }
    return self;
}

#pragma mark - ---------- Peripeeral Delegate ----------
#pragma mark 外围设备服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    if (error) {
        NSLog(@"\n Discover services fail, error:%@", [error localizedDescription]);
        return;
    }
    NSLog(@"\n Scan peripheral：%@ -> Serivices：%@", peripheral.name, peripheral.services);
    for (CBService *service in peripheral.services) {
        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]]) {
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
}

#pragma mark 外围设备服务特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(nonnull CBService *)service error:(nullable NSError *)error {
    if (error) {
        NSLog(@"\n Scan peripereal：%@ -> UUID：%@ -> error：%@", peripheral.name, service.UUID, [error localizedDescription]);
        return;
    }
    [service.characteristics enumerateObjectsUsingBlock:^(CBCharacteristic * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"\n Service.characteristic —> %@",obj);
    }];
    [service.characteristics enumerateObjectsUsingBlock:^(CBCharacteristic * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([[obj UUID] isEqual:[CBUUID UUIDWithString:@"FFF1"]]) {
            //Notificate notice
            self.notiC = obj;
            [peripheral setNotifyValue:YES forCharacteristic:obj];
        } else if ([[obj UUID] isEqual:[CBUUID UUIDWithString:@"FFF2"]]) {
            //Write to peripheral
            self.writeC = obj;
            if (self.isFirstCommandType_SYS_INFO) {
                [self analysisCommand:CommandType_SYS_INFO];
                [self analysisCommand_SYS_CONTROL:CONTROL_STOP];
                self.isFirstCommandType_SYS_INFO = NO;
            }
        }
    }];
}

#pragma mark 接收外围设备的数据
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"\n Scan peripheral'%@' characteristic failed, error ->\n%@", peripheral.name, [error localizedDescription]);
    }
    NSLog(@"\n Characteristic.UUID:\n%@,\n characteristic.value:%@", characteristic.UUID.UUIDString, characteristic.value);
    if ([characteristic.UUID.UUIDString isEqualToString:@"FFF1"]) {
        NSData *characteristicData = characteristic.value;
        [self analysisData:characteristicData];
    }
}

#pragma mark - ---------- Send Command && Analysis data method ----------
#pragma mark 发送数据
- (void)analysisCommand:(CommandType)commandType {
    switch (commandType) {
        case CommandType_SYS_INFO: {
            for (int i = 0; i < 5; i ++) {
                [self analysisCommand_SYS_INFO:calculate_16(i)];
            }
        }
            break;
        case CommandType_SYS_STATUS: {
            [self analysisCommand_SYS_STATUS];
        }
            break;
        case CommandType_SYS_DATA: {
            [self analysisCommand_SYS_DATA:calculate_16(4)];
        }
            break;
        case CommandType_SYS_CONTROL: {
            
        }
            break;
        case CommandType_SYS_KEY: {
            
        }
            break;
    }
}

#pragma mark 接收数据
- (void)analysisData:(NSData *)data {
    Byte *bytes = (Byte *)[data bytes];
    NSMutableArray *bytesMArr = [NSMutableArray array];
    for(int i = 0; i < [data length]; i ++){
        [bytesMArr addObject:[NSString stringWithFormat:@"%d",bytes[i]]];
    }
    NSMutableString *dataMStr = [NSMutableString string];
    [bytesMArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [dataMStr appendString:obj];
        if (idx != bytesMArr.count - 1) {
            [dataMStr appendString:@","];
        }
    }];
    NSLog(@"\n Elicit data string:%@", dataMStr);
    
    int cmd = [[bytesMArr objectAtIndex:1] intValue];//通过指令分别进行处理
    switch (cmd) {
        case CommandType_SYS_INFO: {
            [self analysisData_SYS_INFO_DataArray:bytesMArr];
        }
            break;
        case CommandType_SYS_STATUS: {
            [self analysisData_SYS_STATUS_DataArray:bytesMArr];
        }
            break;
        case CommandType_SYS_DATA: {
            [self analysisData_SYS_DATA_DataArray:bytesMArr];
        }
            break;
        case CommandType_SYS_CONTROL: {
            [self analysisData_SYS_CONTROL_DataArray:bytesMArr];
        }
            break;
        case CommandType_SYS_KEY: {
            
        }
            break;
    }
}

#pragma mark - ---------- 发送数据 ----------
#pragma mark 获取设备信息
- (void)analysisCommand_SYS_INFO:(SYS_INFO)SYS_INFO {
    NSData *data;
    switch (SYS_INFO) {
        case INFO_MODEL: {
            data = [self INFO_MODEL_CommandData:SYS_INFO];
        }
            break;
        case INFO_DATE:
        case INFO_SPEED:
        case INFO_INCLINE:
        case INFO_TOTAL: {
            data = [self SYS_INFO_CommandData:SYS_INFO];
        }
            break;
        default:
            break;
    }
    [self.peripheral writeValue:data forCharacteristic:self.writeC type:CBCharacteristicWriteWithResponse];
}

- (NSData *)INFO_MODEL_CommandData:(SYS_INFO)commandData {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yy-MM-dd-HH-mm-ss";
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSArray *dateArr = [dateStr componentsSeparatedByString:@"-"];
    int command_second = 0x00;
    int yyInt = calculate_16([dateArr[0] intValue]);
    int MMInt = calculate_16([dateArr[1] intValue]);
    int ddInt = calculate_16([dateArr[2] intValue]);
    int HHInt = calculate_16([dateArr[3] intValue]);
    int mmInt = calculate_16([dateArr[4] intValue]);
    int ssInt = 0x00;
    int xor = 0x50 ^ command_second ^ yyInt ^ MMInt ^ ddInt ^ HHInt ^ mmInt ^ ssInt;
    Byte dataArr[11];
    dataArr[0] = startCode;
    dataArr[1] = 0x50;
    dataArr[2] = commandData;
    dataArr[3] = yyInt;//年
    dataArr[4] = MMInt;//月
    dataArr[5] = ddInt;//日
    dataArr[6] = HHInt;//时
    dataArr[7] = mmInt;//分
    dataArr[8] = ssInt;//秒
    dataArr[9] = xor;//异或值
    dataArr[10] = endCode;
    return [[NSData alloc] initWithBytes:dataArr length:11];
}

- (NSData *)SYS_INFO_CommandData:(int)commandData {
    int xor = 0x50 ^ commandData;
    Byte dataArr[5];
    dataArr[0] = startCode;
    dataArr[1] = 0x50;
    dataArr[2] = commandData;
    dataArr[3] = xor;
    dataArr[4] = endCode;
    return [[NSData alloc] initWithBytes:dataArr length:5];
}

#pragma mark 获取设备状态
- (void)analysisCommand_SYS_STATUS {
    NSData *data;
    data = [self SYS_STATUSWithCommand:0x51];
    [self.peripheral writeValue:data forCharacteristic:self.writeC type:CBCharacteristicWriteWithResponse];
}

- (NSData *)SYS_STATUSWithCommand:(int)command {
    Byte dataArr[4];
    dataArr[0] = startCode;
    dataArr[1] = command;
    dataArr[2] = command;
    dataArr[3] = endCode;
    return [[NSData alloc] initWithBytes:dataArr length:4];
}

#pragma mark 设备数据
- (void)analysisCommand_SYS_DATA:(SYS_DATA)SYS_DATA {
    NSData *data;
    switch (SYS_DATA) {
        case DATA_SPORT: {
            
        }
            break;
        case DATA_INFO: {
            
        }
            break;
        case DATA_SPEED: {
            
        }
            break;
        case DATA_INCLINE: {
            
        }
            break;
        case DATA_CACHE: {
            data = [self DATA_CACHEWithCommandData:SYS_DATA WithTiming:0];
        }
            break;
        default:
            break;
    }
    [self.peripheral writeValue:data forCharacteristic:self.writeC type:CBCharacteristicWriteWithResponse];
}

- (NSData *)DATA_CACHEWithCommandData:(int)commandData WithTiming:(int)timing {
//#warning 时间节点未确定何时传入
    Byte dataArr[5];
    int xor = 0x52 ^ commandData ^ timing;
    dataArr[0] = startCode;
    dataArr[1] = 0x52;
    dataArr[2] = commandData;
    dataArr[3] = xor;
    dataArr[4] = endCode;
    return [[NSData alloc] initWithBytes:dataArr length:5];
}

#pragma mark 设备控制
- (void)analysisCommand_SYS_CONTROL:(SYS_CONTROL)SYS_CONTROL {
    NSData *data;
    switch (SYS_CONTROL) {
        case CONTROL_USER: {
            data = [self CONTROL_USERWithCommandData:SYS_CONTROL];
        }
            break;
        case CONTROL_START: {
            
        }
            break;
        case CONTROL_RUN: {
            data = [self CONTROL_RUNWithCommandData:SYS_CONTROL];
        }
            break;
        case CONTROL_STOP: {
            data = [self CONTROL_STOPWithCommandData:SYS_CONTROL];
        }
            break;
        case CONTROL_SPEED: {
            
        }
            break;
        case CONTROL_INCLINE: {
            
        }
            break;
    }
    [self.peripheral writeValue:data forCharacteristic:self.writeC type:CBCharacteristicWriteWithResponse];
}

- (NSData *)CONTROL_USERWithCommandData:(int)commandData {
    Byte dataArr[12];
    int userId1 = 0x00;
    int userId2 = 0x00;
    int userId3 = 0x00;
    int userId4 = 0x09;
    int weight = 0x70;
    int height1 = 0x01;
    int heitht2 = 0x80;
    int xor = 0x53 ^ commandData ^ userId1 ^ userId2 ^ userId3 ^ userId4 ^ weight ^ height1 ^ heitht2;
    dataArr[0] = startCode;
    dataArr[1] = 0x53;
    dataArr[2] = commandData;
    dataArr[3] = userId1;
    dataArr[4] = userId2;
    dataArr[5] = userId3;
    dataArr[6] = userId4;
    dataArr[7] = weight;
    dataArr[8] = height1;
    dataArr[9] = heitht2;
    dataArr[10] = xor;
    dataArr[11] = endCode;
    return [[NSData alloc] initWithBytes:dataArr length:12];
}

- (NSData *)CONTROL_RUNWithCommandData:(int)commandData {
    Byte dataArr[8];
    int speed = calculate_16(self.speed);
    int gradient = calculate_16(self.gradient);
    int other = 0x00;
    int xor = 0x53 ^ commandData ^ speed ^ gradient ^ other;
    dataArr[0] = startCode;
    dataArr[1] = 0x53;
    dataArr[2] = commandData;
    dataArr[3] = speed;
    dataArr[4] = gradient;
    dataArr[5] = other;
    dataArr[6] = xor;
    dataArr[7] = endCode;
    return [[NSData alloc] initWithBytes:dataArr length:8];
}

- (NSData *)CONTROL_STOPWithCommandData:(int)commandData {
    Byte dataArr[5];
    int xor = 0x53 ^ commandData;
    dataArr[0] = startCode;
    dataArr[1] = 0x53;
    dataArr[2] = commandData;
    dataArr[3] = xor;
    dataArr[4] = endCode;
    return [[NSData alloc] initWithBytes:dataArr length:5];
}

#pragma mark - ---------- 接收数据 ----------
#pragma mark 获取设备信息
- (void)analysisData_SYS_INFO_DataArray:(NSArray *)dataArr {
    int cmd = calculate_16([[dataArr objectAtIndex:2] intValue]);
    NSLog(@"\n SYS_INFO:%d", cmd);
    switch (cmd) {
        case INFO_MODEL: {
            [self INFO_MODEL_DataArray:dataArr];
        }
            break;
        case INFO_DATE: {
            [self INFO_DATE_DataArray:dataArr];
        }
            break;
        case INFO_SPEED: {
            [self INFO_SPEED_DataArray:dataArr];
        }
            break;
        case INFO_INCLINE: {
            [self INFO_INCLINE_DataArray:dataArr];
        }
            break;
        case INFO_TOTAL: {
            [self INFO_TOTAL_DataArray:dataArr];
        }
            break;
    }
}

/// 获取设备机型 (必需实现)
- (void)INFO_MODEL_DataArray:(NSArray *)dataArr {
    
}

/// 获取设备出厂日期 (若不支持可省略)
- (void)INFO_DATE_DataArray:(NSArray *)dataArr {
    
}

/// 获取设备速度参数 (必需实现)
- (void)INFO_SPEED_DataArray:(NSArray *)dataArr {
    __block NSString *highSpeed;
    __block NSString *lowSpeed;
    __block NSString *unit;
    [dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 3) {
            //最高速
            highSpeed = [NSString stringWithFormat:@"%.1f", [obj floatValue] / 10];
        } else if (idx == 4) {
            //最低速
            lowSpeed = [NSString stringWithFormat:@"%.1f", [obj floatValue] / 10];
        } else if (idx == 5) {
            //单位
            unit = [NSString stringWithFormat:@"%@", [obj intValue] == 0 ? @"公里" : @"英里"];
            *stop = YES;
        }
    }];
}

/// 获取设备坡度参数 (若不支持可省略)
- (void)INFO_INCLINE_DataArray:(NSArray *)dataArr {
    __block int gradient_TotalHeight;
    __block int gradient_leve;
    [dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 3) {
            //坡度总高
            gradient_TotalHeight = [obj intValue];
        } else if (idx == 4) {
            //水平坡度
            gradient_leve = [obj intValue];
            *stop = YES;
        }
    }];
}

/// 获取设备累计里程 (若不支持可省略)
- (void)INFO_TOTAL_DataArray:(NSArray *)dataArr {
    
}

#pragma mark 获取设备状态
- (void)analysisData_SYS_STATUS_DataArray:(NSArray *)dataArr {
    int cmd = [[dataArr objectAtIndex:2] intValue];
    switch (cmd) {
        case STATUS_NORMAL: {
            [self STATUS_NORMAL_DataArray:dataArr];
        }
            break;
        case STATUS_END: {
            [self STATUS_END_DataArray:dataArr];
        }
            break;
        case STATUS_START: {
            [self STATUS_START_DataArray:dataArr];
        }
            break;
        case STATUS_RUNNING: {
            [self STATUS_RUNNING_DataArray:dataArr];
        }
            break;
        case STATUS_STOP: {
            [self STATUS_STOP_DataArray:dataArr];
        }
            break;
        case STATUS_ERROR: {
            [self STATUS_ERROR_DataArray:dataArr];
        }
            break;
        case STATUS_SAFETY: {
            [self STATUS_SAFETY_DataArray:dataArr];
        }
            break;
        case STATUS_DISRUN: {
            [self STATUS_DISRUN_DataArray:dataArr];
        }
            break;
    }
    [self updateConnectStatus:cmd];
}

/// 待机状态
- (void)STATUS_NORMAL_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 待机状态...");
}

/// 减速已停机状态(还未返回到待机)
- (void)STATUS_END_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 减速已停机状态(还未返回到待机)...");
    [self updateBLEDataWithDataArr:dataArr];
}

/// 开始启动状态
- (void)STATUS_START_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 开始启动状态...");
    int countdown = [[dataArr objectAtIndex:3] intValue];
    NSLog(@"countdown->%d", countdown);
    [self countdown:countdown];
}

/// 运行中状态
- (void)STATUS_RUNNING_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 运行中状态...");
    [self updateBLEDataWithDataArr:dataArr];
}

/// 减速停止中状态
- (void)STATUS_STOP_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 减速停止中状态...");
    [self updateBLEDataWithDataArr:dataArr];
}

/// 设备故障状态
- (void)STATUS_ERROR_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 设备故障状态...");
}

/// 安全锁状态
- (void)STATUS_SAFETY_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 安全锁状态...");
}

/// 禁止启动状态(设备处于不允许运行状态)
- (void)STATUS_DISRUN_DataArray:(NSArray *)dataArr {
    NSLog(@"\n 禁止启动状态(设备处于不允许运行状态)...");
}

#pragma mark 更新展示数据
- (void)updateBLEDataWithDataArr:(NSArray *)dataArr {
    //速度单位: 0.1km/h
    int speedInt = [[dataArr objectAtIndex:3] intValue];
    self.speed = speedInt;
    float speedf = speedInt / 10;
    NSString *currentSpeed = SF(@"%.1f", speedf);
    //坡度
    NSString *currentGradient = SF(@"%d", [[dataArr objectAtIndex:4] intValue]);
    //时间单位: 1s
    int time1 = [[dataArr objectAtIndex:5] intValue];
    int time2 = [[dataArr objectAtIndex:6] intValue];
    NSString *totalTime = SF(@"%d", time1 + time2 * 256);
    //正计距离单位: 1m
    int distance1 = [[dataArr objectAtIndex:7] intValue];
    int distance2 = [[dataArr objectAtIndex:8] intValue];
    float distancef = (distance1 + distance2 * 256) / 1000;
    NSString *totalDistance = SF(@"%.2f", distancef);
    //热量单位: 0.1大卡
    int kiloCalorie1 = [[dataArr objectAtIndex:9] intValue];
    int kiloCalorie2 = [[dataArr objectAtIndex:10] intValue];
    float kiloCalorief = (kiloCalorie1 + kiloCalorie2 * 256) / 10;
    NSString *totalKilocalorie = SF(@"%.1f", kiloCalorief);
    //步数
    int step1 = [[dataArr objectAtIndex:11] intValue];
    int step2 = [[dataArr objectAtIndex:12] intValue];
    NSString *totalStep = SF(@"%d", step1 + step2 * 256);
    //心率
    NSString *currentHeardRate = SF(@"%@", [dataArr objectAtIndex:13]);
    //当前段数指程式或赛事模式时速度或坡度当前所对应段位置，其它模式未用
    NSString *currentNumberOfSpans = SF(@"%@", [dataArr objectAtIndex:14]);
    HR_BLELinkInfoModel *model = [[HR_BLELinkInfoModel alloc] init];
    model.currentSpeed = currentSpeed;
    model.currentGradient = currentGradient;
    model.totalTime = totalTime;
    model.totalDistance = totalDistance;
    model.totalKilocalorie = totalKilocalorie;
    model.totalStep = totalStep;
    model.currentHeardRate = currentHeardRate;
    model.currentNumberOfSpans = currentNumberOfSpans;
    [self updateBLEDataWithModel:model];
}

#pragma mark 设备数据
- (void)analysisData_SYS_DATA_DataArray:(NSArray *)dataArr {
    int cmd = calculate_16([[dataArr objectAtIndex:2] intValue]);
    NSLog(@"\n SYS_STATUS:%d", cmd);
    switch (cmd) {
        case DATA_SPORT: {
            [self DATA_SPORT_DataArray:dataArr];
        }
            break;
        case DATA_INFO: {
            [self DATA_INFO_DataArray:dataArr];
        }
            break;
        case DATA_SPEED: {
            [self DATA_SPEED_DataArray:dataArr];
        }
            break;
        case DATA_INCLINE: {
            [self DATA_INCLINE_DataArray:dataArr];
        }
            break;
        case DATA_CACHE: {
            [self DATA_CACHE_DataArray:dataArr];
        }
            break;
    }
}

/// 读取当前运动量
- (void)DATA_SPORT_DataArray:(NSArray *)dataArr {
    
}

/// 当前运动信息
- (void)DATA_INFO_DataArray:(NSArray *)dataArr {
    
}

/// 速度数据(程式模式)
- (void)DATA_SPEED_DataArray:(NSArray *)dataArr {
    
}

/// 坡度数据(程式或赛事模式)
- (void)DATA_INCLINE_DataArray:(NSArray *)dataArr {
    
}

/// 指定时间点速度、坡度、心率缓存数据
- (void)DATA_CACHE_DataArray:(NSArray *)dataArr {
    
}

#pragma mark 设备控制
- (void)analysisData_SYS_CONTROL_DataArray:(NSArray *)dataArr {
    int cmd = calculate_16([[dataArr objectAtIndex:2] intValue]);
    NSLog(@"///SYS_CONTROL->\n%d", cmd);
    switch (cmd) {
        case CONTROL_USER: {
            [self CONTROL_USER_DataArray:dataArr];
        }
            break;
        case CONTROL_START: {
            [self CONTROL_START_DataArray:dataArr];
        }
            break;
        case CONTROL_RUN: {
            [self CONTROL_RUN_DataArray:dataArr];
        }
            break;
        case CONTROL_STOP: {
            [self CONTROL_STOP_DataArray:dataArr];
        }
            break;
        case CONTROL_SPEED: {
            [self CONTROL_SPEED_DataArray:dataArr];
        }
            break;
        case CONTROL_INCLINE: {
            [self CONTROL_INCLINE_DataArray:dataArr];
        }
            break;
    }
}

/// 写入用户信息
- (void)CONTROL_USER_DataArray:(NSArray *)dataArr {
    
}

/// 开始启动设备(启动后写入用户信息)
- (void)CONTROL_START_DataArray:(NSArray *)dataArr {
    
}

/// 写入运行速度、坡度
- (void)CONTROL_RUN_DataArray:(NSArray *)dataArr {
    
}

/// 停止设备运行
- (void)CONTROL_STOP_DataArray:(NSArray *)dataArr {
    if (!self.isFirstCommandType_SYS_INFO) {
        [self createANewThreadForTimer];
    }
}

/// 速度数据(程式模式)
- (void)CONTROL_SPEED_DataArray:(NSArray *)dataArr {
    
}

/// 坡度数据(程式或赛事模式)
- (void)CONTROL_INCLINE_DataArray:(NSArray *)dataArr {
    
}

#pragma mark - ||============ Self.delegate response selector ============||
#pragma mark Update connect status
- (void)updateConnectStatus:(SYS_STATUS)status {
    if ([self.delegate respondsToSelector:@selector(updateConnectStatus:)]) {
        [self.delegate updateConnectStatus:status];
    }
}

#pragma mark 启动跑步机倒计时
- (void)countdown:(int)countdown {
    if ([self.delegate respondsToSelector:@selector(countdown:)]) {
        [self.delegate countdown:countdown];
    }
}

#pragma mark Update BLE data
- (void)updateBLEDataWithModel:(HR_BLELinkInfoModel *)model {
    if ([self.delegate respondsToSelector:@selector(updateBLEDataWithModel:)]) {
        [self.delegate updateBLEDataWithModel:model];
    }
}

#pragma mark - ||============ Private method ============||
#pragma mark 创建定时器时时获取"获取设备状态"
- (void)createANewThreadForTimer {
    self.threadForTimer = [[NSThread alloc] initWithTarget:self selector:@selector(newThreadForTimer) object:nil];
    [self.threadForTimer start];
}

- (void)newThreadForTimer {
    self.timer = [NSTimer timerWithTimeInterval:.5f repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self analysisCommand:CommandType_SYS_STATUS];//发送数据_获取设备状态
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

#pragma mark - ||============ Public method ============||
/// 写入坡度、速度
- (void)receiveGradient:(NSString *)gradient {
    self.gradient = [gradient intValue];
    [self analysisCommand_SYS_CONTROL:CONTROL_RUN];
}

/// 视频播放完成停止设备运行
- (void)stopTheEquipmentRunning {
    [self analysisCommand_SYS_CONTROL:CONTROL_STOP];
}

- (void)timerFire {
    [self.timer setFireDate:[NSDate distantPast]];
}

- (void)timerPause {
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)clear {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    if (self.threadForTimer) {
        [self.threadForTimer cancel];
    }
}

@end
